import { RuleChain } from "./rule";

function createTask(
    callback: (...args: any[]) => any,
    ruleChain: RuleChain,
    ...args: any[]
) {
    let lastRunAt = 0;
    let timeOutHandle: NodeJS.Timeout;
    let f = async function () {
        let r = callback(...args);
        if (r instanceof Promise) {
            await r;
        }
        clearTimeout(timeOutHandle);
        lastRunAt = Date.now();

        let nextRunAt = ruleChain.generateNextTime(lastRunAt);

        setTimeout(f, nextRunAt - Date.now());
    };
    let nextRunAt = ruleChain.generateNextTime(lastRunAt);
    timeOutHandle = setTimeout(f, nextRunAt - Date.now());
}

export { createTask };
